package com.example.xlmkotlinwanandroid.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

/**
 *  author : cailei
 *  date : 2022/3/11
 *  description :
 */
abstract class BaseVMFragment<VM : ViewModel> : Fragment() {

    private lateinit var viewModels: VM
    val viewModel: VM get() = viewModels

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return viewBinding(inflater, container)
    }

    abstract fun viewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): View


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
        initViews()
        initData()
        observeViewModel()
    }

    private fun initViewModel() {
        viewModels = ViewModelProvider(this).get(viewModelClass())
    }

    abstract fun initViews()
    abstract fun initData()
    abstract fun observeViewModel()

    /**
     * 获取ViewModel的class
     */
    abstract fun viewModelClass(): Class<VM>
}